import axios from 'axios'
import store from '@/store'
import { MessageBox, Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import config from '../api/config'
import router from './../router'


// create an axios instance
const service = axios.create({
  baseURL: config.webServiceUrl, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 900000// request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (config.url.indexOf('/file/getUploadUrl') !== -1) {
      // config.headers['Content-Type'] = 'multipart/form-data'
      config.timeout = 60 * 60 * 10000
    }
    if (store.getters.token) {
      config.headers['satoken'] = getToken()
    }
    return config
  },
  error => {
    console.log('error:', error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    console.log('响应拦截：', response.data)
    let res = response.data
    let msgs = 'error'
    if (res.code !== 200) {
      // console.log('*************res',res);
      // console.log('*************res.code',res.code);
      switch (res.code) {
        case 401:
          msgs = res.msg ? res.msg : '认证失败'
          logout()
          break;
        case 500:
          msgs = res.msg ? res.msg : '服务器遇到错误，无法完成请求'
          break;
        case 503:
          msgs = res.msg ? res.msg : '服务器目前无法使用'
          break;
        default:
        // Message({
        //   message: msgs ? msgs : 'error',
        //   type: 'error',
        //   duration: 5 * 1000
        // })
      }
    }
    return response.data
    // if (res.success === false) {
    //   Message({
    //     message: res.msg,
    //     type: 'error',
    //     duration: 5 * 1000
    //   })
    //   return Promise.reject(new Error(res.msg || 'Error'))
    // } else {
    //   //如果时请求文件的接口在这里做处理，判断路由名称返回hander参数！！
    //   return response.data
    // }
  },
  error => {
    Message({
      message: "网络连接失败",
      type: "warning",
      duration: 3 * 1000
    });
    console.log('err:', error)
    // if (error.response && error.response.status === 401) {// token过期处理
    //   Message({
    //     message: "身份信息已过期,请重新登陆",
    //     type: "warning",
    //     duration: 3 * 1000
    //   });
    //   router.push({ path: "/login" })
    // }
    return Promise.reject(error)
  }
)

async function logout () {
  await store.dispatch('user/logout')
  router.push(`/login?redirect=${router.fullPath}&moduleIndex=${store.state.app.moduleIndex}`)
}
export default service
